//
//  XTStrategyViewController.m
//  BeautifulHome
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ACE. All rights reserved.
//

#import "XTStrategyViewController.h"
#import "XTStrategyTableViewCell.h"
#import "XTStrategyDetailViewController.h"
#import "XTStrategy.h"
#import "NetworkHandle.h"
#import "UIImageView+WebCache.h"
#import "XTMatchViewController.h"
#import "XTCaseViewController.h"
#import "XTGeomancyViewController.h"
// 下拉刷新
#import "MJRefresh.h"
#import "AppDelegate.h"
#define vBackBarButtonItemName  @"backArrow.png"

@interface XTStrategyViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arr1;
@property (nonatomic, retain) NSMutableArray *arr2;
@property (nonatomic, retain) NSMutableArray *arr3;
@end

@implementation XTStrategyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"装修攻略";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(my)];
    self.arr1 = [NSMutableArray array];
    [self createTableView];
    self.isUpLoading = NO;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    view.backgroundColor = [UIColor brownColor];
    self.tableView.tableHeaderView = view;
    [view release];
    // 轮播图
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    // 设置
    self.automaticallyAdjustsScrollViewInsets = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.tag = 9800;
    // 滚动内容设置
    scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 5, 0);
    // 滑动的偏移量
    scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    // 可以整页翻动
    scrollView.pagingEnabled = YES;
    // 取消滚动条
    scrollView.showsHorizontalScrollIndicator = NO;
    // 签订滚动视图协议
    scrollView.delegate = self;
    // 添加父视图
    [view addSubview:scrollView];
    // 释放
    [scrollView release];
    
    // 把几个缩放视图放在滚动视图上
    // 在第一张前面添加最后一张图片,来回滚动
    UIScrollView *sc0 = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    sc0.tag = 1000;
    sc0.delegate = self;
    [scrollView addSubview:sc0];
    UIImageView *imageView0 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    imageView0.image = [UIImage imageNamed:@"103.jpg"];
    [sc0 addSubview:imageView0];
    [imageView0 release];
    [sc0 release];
    
    UIScrollView *sc1 = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, 150)];
    sc1.tag = 1001;
    sc1.delegate = self;
    [scrollView addSubview:sc1];
    UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    imageView1.image = [UIImage imageNamed:@"101.jpg"];
    imageView1.userInteractionEnabled = YES;
    [sc1 addSubview:imageView1];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1Action:)];
    [imageView1 addGestureRecognizer:tap1];
    [imageView1 release];
    [sc1 release];
    
    UIScrollView *sc2 = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, 150)];
    sc2.tag = 1002;
    sc2.delegate = self;
    [scrollView addSubview:sc2];
    UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    imageView2.image = [UIImage imageNamed:@"102.jpg"];
    imageView2.userInteractionEnabled = YES;
    [sc2 addSubview:imageView2];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap2Action:)];
    [imageView2 addGestureRecognizer:tap2];
    [imageView2 release];
    [sc2 release];
    
    UIScrollView *sc3 = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width*3, 0, self.view.frame.size.width, 150)];
    sc3.tag = 1003;
    sc3.delegate = self;
    [scrollView addSubview:sc3];
    UIImageView *imageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    imageView3.image = [UIImage imageNamed:@"103.jpg"];
    imageView3.userInteractionEnabled = YES;
    [sc3 addSubview:imageView3];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap3Action:)];
    [imageView3 addGestureRecognizer:tap3];
    [imageView3 release];
    [sc3 release];
    // 在最后一张后面放上第一张图片
    // 缩放页面
    UIScrollView *sc4 = [[UIScrollView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 4, 0, self.view.frame.size.width, 150)];
    sc4.tag = 1004;
    sc4.delegate = self;
    [scrollView addSubview:sc4];
    UIImageView *imageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    imageView4.image = [UIImage imageNamed:@"101.jpg"];
    [sc4 addSubview:imageView4];
    [imageView4 release];
    [sc4 release];
    
    // UIPageControl 页码控制器
    UIPageControl *page = [[UIPageControl alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 120, 130, 150, 30)];
    page.tag = 1200;
    // 设置需要几个圆点
    page.numberOfPages = 3;
    // 设置当前亮点在第几位
    page.currentPage = 0;
    // 未选中圆点的颜色
    page.pageIndicatorTintColor = [UIColor lightGrayColor];
    // 当前圆点颜色
    page.currentPageIndicatorTintColor = [UIColor darkGrayColor];
    // 绑定响应事件
    [page addTarget:self action:@selector(page:) forControlEvents:UIControlEventValueChanged];
    [view addSubview:page];
    [page release];
    
    // 定时器
    NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    NSLog(@"%@", t);
    // 上拉下拉功能
    [self addHeader];
    [self addFooter];
    
}
- (void)my
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed)
    {
        [tempAppDelegate.LeftSlideVC openLeftView];
    }
    else
    {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }
}
- (void)nextPage
{
    UIScrollView *scrollView = (UIScrollView *)[self.view viewWithTag:9800];
    CGFloat i = scrollView.contentOffset.x;
    if (i >= self.view.frame.size.width * 3) {
        scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }
    else if (i < self.view.frame.size.width * 3) {
        scrollView.contentOffset = CGPointMake(self.view.frame.size.width + i, 0);
    }
}
- (void)getData:(NSInteger)nextCursor
{
// 参数1: 网络接口
// 参数2: 返回数据的Block 参数result中是网络请求的返回数据
    NSString *url = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/ideabook?start=%ld&count=10&user=(null)&tag=%%E5%%85%%A8%%E9%%83%%A8", nextCursor];
    [NetworkHandle getDataWithURL:url completion:^(id result) {
        // result为请求接口的返回数据
        //NSLog(@"%@", result);
        self.nextCursor = [[result objectForKey:@"start"] integerValue] + 10;
        NSLog(@"~~~~~%ld", self.nextCursor);
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.arr1 removeAllObjects];
        }
        NSArray *arr = [result objectForKey:@"ideabooks"];
        for (NSDictionary *dic in arr) {
            XTStrategy *strategy = [[XTStrategy alloc] initWithDic:dic];
            strategy.sDescription = [dic objectForKey:@"description"];
            [_arr1 addObject:strategy];
            [strategy release];
        }
        //NSLog(@"~~~~~~%@", _arr1);
        //NSLog(@"~~%@", [_arr1[0] sDescription]);
        [self.tableView footerEndRefreshing];//结束底部刷新效果
        [self.tableView headerEndRefreshing];//结束头部刷新效果
        [self.tableView reloadData];
    }];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIScrollView *scroll = (UIScrollView *)[self.view viewWithTag:9800];
    if(scroll.contentOffset.x < self.view.frame.size.width ) {
        scroll.contentOffset = CGPointMake(self.view.frame.size.width * 3, 0);
    }
    if (scroll.contentOffset.x > self.view.frame.size.width * 3) {
        scroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIPageControl *p = (UIPageControl *)[self.view viewWithTag:1200];
    p.currentPage = scrollView.contentOffset.x / self.view.frame.size.width - 1;
}
#pragma mark - pageControl 响应方法
- (void)page:(UIPageControl *)page
{
    UIScrollView *s = (UIScrollView *)[self.view viewWithTag:9800];
    s.contentOffset = CGPointMake(self.view.frame.size.width + page.currentPage * self.view.frame.size.width, 0);
}
- (void)tap1Action:(UIGestureRecognizer *)tap1
{
    XTMatchViewController *mVC = [[[XTMatchViewController alloc] init] autorelease];
    [self.navigationController pushViewController:mVC animated:YES];
}
- (void)tap2Action:(UIGestureRecognizer *)tap2
{
    XTCaseViewController *cVC = [[[XTCaseViewController alloc] init] autorelease];
    [self.navigationController pushViewController:cVC animated:YES];
}
- (void)tap3Action:(UIGestureRecognizer *)tap3
{
    XTGeomancyViewController *gVC = [[[XTGeomancyViewController alloc] init] autorelease];
    [self.navigationController pushViewController:gVC animated:YES];
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0 , self.view.frame.size.width, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 80;
    _tableView.tag = 1100;
    [self.view addSubview:_tableView];
    [_tableView release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr1.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    XTStrategyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (!cell) {
        cell = [[XTStrategyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    XTStrategy *str = _arr1[indexPath.row];
    cell.label1.text = str.title;
    cell.label2.text = str.sDescription;
    self.arr2 = [str.photos mutableCopy];
    NSString *string = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w640_h0_m0.jpg", [_arr2[0] objectForKey:@"id"]];
    NSURL *url = [NSURL URLWithString:string];
    [cell.myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"3-1"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中阴影效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XTStrategyDetailViewController *sdVC = [[[XTStrategyDetailViewController alloc] init] autorelease];
    XTStrategy *s1 = _arr1[indexPath.row];
    sdVC.strategy = s1;
    sdVC.name = [s1.user objectForKey:@"userName"];
    sdVC.s2 = s1.photos;
    
    [self.navigationController pushViewController:sdVC animated:YES];
}
#pragma mark --下拉刷新
- (void)addHeader
{
    __block XTStrategyViewController *sVC = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        sVC.isUpLoading = NO;//标记为下拉操作
        [sVC getData:0];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
}
#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block XTStrategyViewController *sVC = self;
    
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        sVC.isUpLoading = YES;//标记为上拉操作
        [sVC getData:sVC.nextCursor];//请求更多数据
        
    }];
}
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    //    NSLog(@"viewWillDisappear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
//}
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    //    NSLog(@"viewWillAppear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
